import type { UniqueIdentifier } from '@dnd-kit/core';

export interface FlattenedItem extends TreeItem {
    parentId: UniqueIdentifier | null;
    depth: number;
    index: number;
    seq: number
}

export interface TreeItem {
    id: UniqueIdentifier;
    cmd: string;
    target: string;
    value: any;
    description?: string;
    children?: TreeItem[];
    collapsed?: boolean;
    breakPoint?: boolean;
}

export type TreeItems = TreeItem[];


// 展开增加并添加end
export const flattenTreeForRun = (treeData: TreeItems) => {
    const items: any = []
    const flatten = (list: any, parentId: any = null, depth: any = 0) => {
        list.forEach(({ children, ...item }: any) => {

            items.push({
                ...item,
                parentId,
                depth,
                seq: items.filter((item: TreeItem) => item.cmd !== 'end').length + 1
            })

            if (/^(do|while|forEach|times|if|elseif|else)$/.test(item.cmd)) {
                flatten(children || [], item.id, depth + 1);
                items.push({
                    id: window.crypto.randomUUID(),
                    cmd: 'end',
                    value: '',
                    target: '',
                    parentId,
                    depth,
                    seq: -1 // 页面看不到设置为seq
                })
            }
        })
    }
    flatten(treeData, null, 0)
    return items
}

// 展开树，读取源数据时使用
export function flattenTree(items: TreeItems): FlattenedItem[] {
    let seq = 0;
    const flatten = (
        items: TreeItems,
        parentId: UniqueIdentifier | null = null,
        depth = 0,
    ): FlattenedItem[] => {
        return items.reduce<FlattenedItem[]>((acc, item, index) => {
            // 如果id为空，则生成一个随机id

            item.id = item.id ?? window.crypto.randomUUID()
            seq++;

            const {
                children,
                ...others
            } = item

            return [
                ...acc,
                { ...others, parentId, depth, index, seq },
                ...flatten(children || [], item.id, depth + 1),
            ];
        }, []);
    }
    return flatten(items);
}

// 构建树，保存为源数据时使用
export function buildTree(flattenedItems: FlattenedItem[]): TreeItems {
    const root: TreeItem = { id: 'root', cmd: '', target: '', value: '', children: [] };
    const nodes: Record<string, TreeItem> = { [root.id]: root };
    const items = flattenedItems.map((item) => ({ ...item, children: [] }));

    for (const item of items) {
        const { id, children, ...props } = item;
        const parentId = item.parentId ?? root.id;
        const parent = nodes[parentId] ?? findItem(items, parentId);
        if (!parent.children) {
            parent.children = []
        }
        nodes[id] = { id, children, ...props };
        parent.children.push(item);
    }

    return root.children || [];
}

// 查找item
export function findItem(items: TreeItem[], itemId: UniqueIdentifier) {
    return items.find(({ id }) => id === itemId);
}

// 删除后代
export function removeItem(
    items: FlattenedItem[],
    ids: UniqueIdentifier[]
) {
    const excludeParentIds = [...ids];

    return items.filter((item) => {
        if (item.parentId && excludeParentIds.includes(item.parentId)) {
            excludeParentIds.push(item.id);
            return false;
        }
        return true;
    });
}